//
//  CourseItemViewController.m
//  ShowYork
//
//  Created by hxh on 2020/8/30.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "LessonItemViewController.h"
#import "LessonDetailViewController.h"
#import "LessonHotCell.h"

#import "UserInfoModel.h"
#import "LessonPlanModel.h"
#import "LessonPageItemModel.h"
@interface LessonItemViewController ()<UITableViewDelegate,UITableViewDataSource,LessonHotCellDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,copy)NSArray *dataArray;
@property (nonatomic,assign)XHCourseItemType itemType;
@property (nonatomic,assign)NSInteger categoryId;
@property (nonatomic,assign)NSInteger subjectId;
@property (nonatomic,strong)UIImageView *noDataImgView;
@property (nonatomic,strong)UILabel *noDataLb;

@end

@implementation LessonItemViewController

- (instancetype)initWithItemType:(XHCourseItemType)itemType categoryId:(NSInteger)categoryId subjectId:(NSInteger)subjectId{
    if (self = [super init]) {
        self.itemType = itemType;
        self.categoryId = categoryId;
        self.subjectId = subjectId;
    }
    return self;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([RPAppManager isShowNetworkView]) {
        @zf_weakify(self)
        [self showNetworkErrorWithNavTitle:@"" completeBlock:^{
           @zf_strongify(self)
            [self setUI];
            [self loadDataSource];
        } cancelBlock:^{
            @zf_strongify(self)
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else{
        [self setUI];
        [self loadDataSource];
    }
    [self registNote];
    // Do any additional setup after loading the view.
}

- (void)setUI{
 
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        }else{
            make.top.equalTo(self.view.mas_top);
            make.right.equalTo(self.view.mas_right);
            make.left.equalTo(self.view.mas_left);
            make.bottom.equalTo(self.view.mas_bottom);
        }
    }];
    
    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"course_noData_tag"]];
    [self.view addSubview:self.noDataImgView];
    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    self.noDataLb = [[UILabel alloc]init];
    self.noDataLb.text = @"无内容";
    self.noDataLb.textColor = C153;
    self.noDataLb.font = font(12);
    self.noDataLb.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.noDataLb];
    
    [self.noDataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.noDataImgView.mas_bottom).offset(8);
    }];
    
    self.noDataImgView.hidden = YES;
    self.noDataLb.hidden = YES;
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.backgroundColor = [UIColor whiteColor];
    

}

- (void)loadDataSource{
    [self showDataLoadState];
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadPageListSource];
    });
   
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self hideDataLoadLoadState];
        [self.tableView reloadData];
    });    
}

- (void)loadPageListSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    if (self.itemType == XHCOURSEITEMHOT) {
        param[@"type"] = @(1);
    }
    if (self.itemType == XHCOURSEITEMRECOMMEND) {
        param[@"type"] = @(2);
    }
    if (self.itemType == XHCOURSEITEMALL) {
        param[@"subjectId"] = @(self.subjectId);
    }
    if (self.categoryId != -1) {
        param[@"categoryId"] = @(self.categoryId);
    }
    param[@"md5"] = [RPAppManager md5StrWithApi:GetLessons];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetLessons) parames:param success:^(id responseObj) {
        self.dataArray = [LessonPageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        self.noDataLb.hidden = self.dataArray.count > 0;
        self.noDataImgView.hidden = self.dataArray.count > 0;
        [self.tableView reloadData];
    } failure:^(id error) {
        
    }];
}

- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDataSource) name:@"updateUserInfoSource" object:nil];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LessonHotCell *cell = [LessonHotCell cellWithTableView:tableView];
    [cell setCurrentModel:self.dataArray[indexPath.row]];
    [cell isHideLine:self.dataArray.count - 1 == indexPath.row];
    cell.delegate = self;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}


- (void)addorRemoveCourseHotPlanAtCurrentModel:(LessonPageItemModel *)model{

    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lessonId"] = model.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:AddUserPlanList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddUserPlanList) parames:param success:^(id responseObj) {
        model.isSeleted = YES;

        NSMutableArray *arr = [[RPAppManager getOwnerPlanIds] mutableCopy];
        [arr addObject:model.id];
        [RPAppManager saveUserPlanIdsWithPlans:arr];

        // 取出对应的
        NSInteger idx = [self.dataArray indexOfObject:model];
        if (idx != -1) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"已加入学习计划" duration:2 finishHandler:nil];

        [[NSNotificationCenter defaultCenter]postNotificationName:@"updateStudyList" object:nil];

    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
   
}

- (void)selectedCaurseAtCurrentModel:(LessonPageItemModel *)model{
    [MobClick event:@"lesson_show_total" attributes:@{@"enter":@"lesson_list"}];
    LessonDetailViewController *dtlVC = [[LessonDetailViewController alloc]init];
    dtlVC.lessonId = model.id;
    [self.navigationController pushViewController:dtlVC animated:YES];
    __weak typeof(self)weakSelf = self;
    dtlVC.updateCourseStatus = ^(NSNumber * _Nonnull lessonId) {
        model.isSeleted = YES;
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.tableView reloadData];
    };
}


@end
